<template>
  <div class="infoWrapper">
    <div class="info">
      <div class="left">
        <div style="display: flex; margin-bottom: 10px">
          <!-- 学校选择 -->
          <div class="infoItem">
            <el-select
              v-model="school.activeItem"
              placeholder="学校"
              style="width: 200px"
            >
              <el-option
                v-for="item in school.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 角色选择 -->
          <div class="infoItem">
            <el-select v-model="roleSelect.activeItem">
              <el-option
                v-for="item in roleSelect.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 学年阶段选择 -->
          <div class="infoItem">
            <el-select v-model="versionSelect.activeItem">
              <el-option
                v-for="item in versionSelect.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 输入设备阶段选择 -->
          <div class="infoItem">
            <el-select v-model="inputDeviceSelect.activeItem">
              <el-option
                v-for="item in inputDeviceSelect.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 起止时间 -->
          <div class="infoItem">
            <el-date-picker
              v-model="timeSelect.activeItem"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>

          <div class="infoItem">
            共<span>{{ instructSum }}</span
            >条指令
          </div>
        </div>
        <div style="display: flex;">
          <!-- 响应类型 -->
          <div class="infoItem">
            <el-select v-model="replyType.activeItem" placeholder="全部">
              <el-option
                v-for="item in replyType.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 指令处理状态 -->
          <div class="infoItem">
            <el-select v-model="status.activeItem" placeholder="状态">
              <el-option
                v-for="item in status.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>

      <div class="right">
        <el-input
          v-model="searchInstructStr"
          placeholder="按用户问题/用户ID搜索"
          class="input infoItem"
          clearable
          @keyup.enter.native="searchInstruct"
          @clear="searchInstruct"
        >
          <template #append>
            <el-button :icon="Search" @click="searchInstruct" />
          </template>
        </el-input>
        <el-button @click="exportRelearn"> 导出 </el-button>
      </div>
    </div>

    <div class="content">
      <slot
        :identityData="identityData"
        :tableData="tableData"
        :schoolMap="schoolMap"
        :deleteInstructs="deleteInstructs"
        :remarkInstructs="remarkInstructs"
        :refresh="refresh"
        :changeInstructOpenType="changeInstructOpenType"
        :updatePageNum="updatePageNum"
        :updatePageSize="updatePageSize"
        :totalSize="totalSize"
      ></slot>
    </div>
  </div>
</template>

<script setup>
import {
  api_deleteRelearn,
  api_listaaa,
  api_relearnExport,
  api_remarkRelearn,
} from "@/api/manage";
import { getAllSchoolInfo } from "@/utils/CommonRequest";
import { Search } from "@element-plus/icons-vue";
import { ElLoading, ElMessage } from "element-plus";
import { onMounted, reactive, ref, watch } from "vue";
import { RELEARN_STATUS_DATA } from "../enum";

const props = defineProps({
  openDraw: Function,
  lastDownloadTime: String,
});

const pageNum = ref(1);
const pageSize = ref(10);
const totalSize = ref(0);

const status = reactive({
  data: [{value: -1, label: "全部状态"}, ...RELEARN_STATUS_DATA],
  activeItem: -1,
});

const school = reactive({
  data: [],
  activeItem: "",
});
const schoolMap = ref(new Map());

const timeSelect = reactive({
  activeItem: "",
});

const userReaction = reactive({
  data: [
    { label: "所有异常结果", value: "-1" },
    { label: "用户不同意", value: 2 },
    { label: "用户同意", value: 1001 },
  ],
  activeItem: "-1",
});

const replyType = reactive({
  data: [
    { label: "全部结果", value: "-1" },
    { label: "正常反馈", value: "1" },
    { label: "异常反馈", value: "2" },
    { label: "用户认同", value: "3" },
    { label: "用户不认同", value: "4" },
  ],
  activeItem: "-1",
});

const roleSelect = reactive({
  data: [
    { label: "全部角色", value: "-1" },
    { label: "管理员", value: "ADMIN" },
    { label: "教师", value: "TEACHER" },
    { label: "学生", value: "STUDENT" },
    { label: "家长", value: "PARENT" },
  ],
  activeItem: "-1",
});

const versionSelect = reactive({
  data: [
    { label: "全部学年阶段", value: "-1" },
    { label: "中小学", value: "2" },
    { label: "大学", value: "1" },
    { label: "中职", value: "4" }
  ],
  activeItem: "-1",
});

const inputDeviceSelect = reactive({
  data: [
    { label: "全部输入设备", value: "-1" },
    { label: "PC端", value: "1" },
    { label: "移动端", value: "2" }
  ],
  activeItem: "-1",
});

const instructSum = ref(0);
const searchInstructStr = ref(""); //输入框搜索
const originTableData = ref([]);
const tableData = ref([]);
const identityData = ref([]);

const updatePageNum = (num) => {
  pageNum.value = num;
  fetchInstruct({});
}

const updatePageSize = (num, size) => {
  pageNum.value = num;
  pageSize.value = size;
  fetchInstruct({});
}

const changeInstructOpenType = (code) => {
  tableData.value?.forEach((center) => {
    center.robotInstructModuleDTOS?.forEach((curModule) => {
      curModule.robotInstructNameAndSentenceDTOS?.forEach((instruct) => {
        if (instruct.instructCode === code) {
          instruct.flag = instruct.flag === 0 ? 1 : 0;
        }
      });
    });
  });
};

const refresh = async () => {
  initSchoolInfo();

  fetchInstruct({
    status: status.activeItem,
    schoolId: school.activeItem,
  });
};

const initSchoolInfo = async () => {
  const { ErrCode, Data } = await getAllSchoolInfo();
  if (ErrCode !== 0) {
    ElMessage.error("获取学校信息失败");
    return;
  }
  const schoolData = Data?.map((v) => {
    schoolMap.value.set(v.SchoolID, v.schoolName);
    return {
      value: v.SchoolID,
      label: `${v.schoolName}(${v.SchoolID})`,
    };
  });

  school.data = schoolData;
  school.data.unshift({
    value: -1,
    label: "全部学校",
  });
  school.activeItem = schoolData?.[0]?.value ?? "";
};

defineExpose({ refresh });

onMounted(() => {
  // 通过Manage的mounted后调用此方法
  // refresh();
});

/**
 * 输入框搜索
 */
const searchInstruct = () => {
  fetchInstruct({});
};

const fetchInstruct = async (d) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "transparent",
  });

  // 开始时间和结束时间
  let startDate = "",
    endDate = "";
  if (timeSelect.activeItem) {
    startDate = timeSelect?.activeItem?.[0]?.getTime();
    endDate = new Date(timeSelect?.activeItem?.[1]);
    endDate.setDate(endDate.getDate() + 1);

    endDate = endDate.getTime();
  }
  // 其它筛选条件
  d.startDate = d.startDate || startDate;
  d.endDate = d.endDate || endDate;
  d.schoolId = d.schoolId || school.activeItem;
  d.status = d.status || status.activeItem;
  d.userReaction = d.userReaction || userReaction.activeItem;
  d.replyType = d.replyType || replyType.activeItem;
  d.role = d.role || roleSelect.activeItem;
  d.version = d.version || versionSelect.activeItem;
  d.inputDevice = d.inputDevice || inputDeviceSelect.activeItem;
  d.keyWord = searchInstructStr.value;
  d.pageNum = pageNum.value;
  d.pageSize = pageSize.value;

  if (d.schoolId === -1) {
    d.schoolId = "";
  }
  if (d.status == "-1") {
    delete d.status;
  }
  if (d.userReaction == "-1") {
    delete d.userReaction;
  }
  if (d.replyType == "-1") {
    delete d.replyType;
  }
  if (d.role == "-1") {
    delete d.role;
  }
  if (d.version == "-1") {
    delete d.version;
  }
  if (d.inputDevice == "-1") {
    delete d.inputDevice;
  }

  try {
    const { data, success, msg } = await api_listaaa({
      ...d,
    });
    if (!success) {
      throw new Error("获取指令失败,接口返回:" + msg);
    }
    const buriedDataList = data?.itemList?.[0];
    originTableData.value = buriedDataList;
    tableData.value = buriedDataList;
    totalSize.value = data?.total;
    instructSum.value = totalSize.value;

  } catch (e) {
    console.log('e = ', e)
    ElMessage.error("获取数据失败");
  }

  loading.close();
};

const deleteInstructs = async (index, row) => {
  const r = await api_deleteRelearn({
    id: row.id,
    schoolId: row.schoolId,
  });

  if (r.success === true) {
    ElMessage.success(`删除成功`);
    fetchInstruct({});
  } else {
    ElMessage.error(`${row.userQuestion}删除失败,接口返回:${r.msg}`);
  }
};

const exportRelearn = async () => {
  let s = status.activeItem;
  let schoolId = school.activeItem;
  let userReactionValue = userReaction.activeItem;
  let replyTypeValue = replyType.activeItem;
  let role = roleSelect.activeItem;
  let version = versionSelect.activeItem;
  let inputDevice = inputDeviceSelect.activeItem;
  let keyWord = searchInstructStr.value;

  let startDate = "",
    endDate = "";
  if (timeSelect.activeItem) {
    startDate = timeSelect?.activeItem?.[0]?.getTime();
    endDate = new Date(timeSelect?.activeItem?.[1]);
    endDate.setDate(endDate.getDate() + 1);

    endDate = endDate.getTime();
  }

  if (s == -1) {
    s = "";
  }
  if (schoolId == -1) {
    schoolId = "";
  }
  if (userReactionValue == "-1") {
    userReactionValue = "";
  }
  if (replyTypeValue == "-1") {
    replyTypeValue = "";
  }
  if (role == "-1") {
    role = "";
  }
  if (version == "-1") {
    version = "";
  }
  if (inputDevice == "-1") {
    inputDevice = "";
  }

  let r = null;
  await api_relearnExport({
    status: s,
    schoolId,
    startDate,
    endDate,
    keyWord,
    replyType: replyTypeValue,
    role,
    version,
    inputDevice,
    userReaction: userReactionValue,
  })
    .then((res) => {
      r = res;
    })
    .catch((err) => {});

  const a = document.createElement("a");
  const url = window.URL.createObjectURL(r);
  a.href = url;
  a.download = "人工智能机器人-指令再学习.xlsx"; //这里最重要。如果不加后缀。保存的文件就会异常或者乱码。一定要写文件后缀类型
  a.click();
};

const remarkInstructs = async (index, row) => {
  const r = await api_remarkRelearn({
    id: row.id,
    remark: row.remark,
  });

  if (r.success === true) {
    ElMessage.success(`备注成功`);
    fetchInstruct({});
  } else {
    ElMessage.error(`备注失败,接口返回:${r.msg}`);
  }
};

const emits = defineEmits(["visibleChange"]);

// 2024-12-13：因为这两个select框是通过代码赋值，所以系统启动后会触发watch
const isFirstShowStatus = ref(true);
const isFirstShowSchool = ref(true);
watch(
  () => status.activeItem,
  (newVal) => {
    if (isFirstShowStatus.value){
      isFirstShowStatus.value = false;
      return;
    }
    fetchInstruct({
      status: newVal,
    });
  }
);
watch(
  () => school.activeItem,
  (newVal) => {
    if (isFirstShowSchool.value){
      isFirstShowSchool.value = false;
      return;
    }
    fetchInstruct({
      schoolId: newVal,
    });
  }
);
watch(
  () => roleSelect.activeItem,
  (newVal) => {
    fetchInstruct({
      role: newVal,
    });
  }
);
watch(
  () => versionSelect.activeItem,
  (newVal) => {
    fetchInstruct({
      version: newVal,
    });
  }
);
watch(
  () => inputDeviceSelect.activeItem,
  (newVal) => {
    fetchInstruct({
      inputDevice: newVal,
    });
  }
);

watch(
  () => timeSelect.activeItem,
  (newVal) => {
    if (!newVal) {
      //清空了日期
      fetchInstruct({});
      return;
    }

    let startDate = new Date(newVal[0]);
    let endDate = new Date(newVal[1]);
    endDate.setDate(endDate.getDate() + 1);

    fetchInstruct({
      schoolId: school.activeItem,
      status: status.activeItem,
      startDate: startDate.getTime(),
      endDate: endDate.getTime(),
      userReaction: userReaction.activeItem,
    });

    // let tempArr = [];
    // originTableData.value.forEach(item => {
    //   let operDate = new Date(item.gmtModified);
    //   if (operDate.getTime() >= startDate.getTime() && operDate.getTime() <= endDate.getTime()) {
    //     tempArr.push(item);
    //   }
    // });

    // refreshTableData(tempArr)
  }
);
watch(
  () => userReaction.activeItem,
  (newVal) => {
    fetchInstruct({
      userReaction: newVal,
    });
  }
);
watch(
  () => replyType.activeItem,
  (newVal) => {
    fetchInstruct({
      replyType: newVal,
    });
  }
);
</script>

<style lang="scss" scoped>
.infoWrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .info {
    margin: 15px 30px;
    display: flex;
    justify-content: space-between;
    :deep(.el-select) {
      width: 130px;
      span {
        font-weight: normal;
        color: rgba(0, 0, 0, 0.88);
      }
    }
    .infoItem {
      display: flex;
      align-items: center;
    }
    .infoItem + .infoItem {
      margin-left: 20px;
    }
    .left {
      display: flex;
      flex-direction: column;

      font-weight: 600;
      font-size: 17px;
      color: #555555;
    }
    .right {
      display: flex;
      align-items: flex-start;
      .input {
        width: 350px;
        margin-right: 5px;
      }
      .createBtn {
      }
    }
  }
  .content {
    flex: 1;
    min-height: 0;
  }
}
</style>
